package com.example.netty.nio.reactor.multiplethread;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * NIO 服务端 基于Reactor模型的多线程模型
 *
 * @author LSQ
 * @since 2023/2/19 9:49
 */
public class Server {

    public static void main(String[] args) {
        try {
            ServerSocketChannel channel = ServerSocketChannel.open();
            channel.configureBlocking(false);
            channel.bind(new InetSocketAddress(8888));
            Selector selector = Selector.open();
            channel.register(selector, SelectionKey.OP_ACCEPT);

            // 子线程用于及逆行具体的IO操作 用线程池进行管理
            ExecutorService executorService = Executors.newFixedThreadPool(10);

            // 主线程用来接收客户端的连接
            while (selector.select() > 0) {
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();
                    if (selectionKey.isAcceptable()) {
                        // 处理客户端的连接
                        System.out.println(Thread.currentThread().getName() + " ---> 开始处理客户端的连接请求...");
                        SocketChannel socketChannel = channel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()) {
                        executorService.execute(() -> {
                            // 进行IO操作...
                        });
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
